<template>
    <el-dialog :visible.sync="showDialog" title="选择" width="80%" @close='cancel'>
        <el-form class="form myself-form" ref="form" :model="addForm" :rules="submitRules" label-width="120px">
            <el-steps :active="active" v-if="active != 9" simple class="my-steps">
                <el-step title="选择文件"></el-step>
                <el-step title="设置"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <div class="h filediv" v-if="active == 1">
                <el-tree :props="defaultProps" :load="doloadNode" node-key="uuid" ref="tree"
                    :expand-on-click-node="false" lazy show-checkbox>
                    <span class="custom-tree-node" slot-scope="{ node }">
                        <span :class="['name-icon', handleClass(node.data)]">
                            {{ node.data.name }}
                        </span>
                    </span>

                </el-tree>
            </div>
            <div v-if="active == 2">
                <h3 class="add-alike-title">基本信息</h3>
                <div v-if="model_id == null">
                    <el-form-item label="范围" prop="visibility">
                        <el-radio-group v-model="addForm.visibility">
                            <el-radio :label="0">私有的</el-radio>
                            <el-radio :label="1">共享的</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="名称" prop="name">
                        <el-input type="text" v-model="addForm.name" />
                    </el-form-item>
                    <el-form-item label="别名" prop="alias">
                        <el-input type="text" v-model="addForm.alias" />
                    </el-form-item>
                    <el-form-item label="描述" prop="desc">
                        <el-input type="textarea" :rows="3" v-model="addForm.desc" />
                    </el-form-item>
                    <el-form-item label="配图">
                        <media-uploader accept=".jpg,.jpeg,.png,.JPG,.JPEG" :src="addForm.avatar"
                            @avatarPath="avatarPath" />
                    </el-form-item>
                    <el-form-item label="标签类型" prop="labels" v-if="business_type<3">
                        <el-select v-model="addForm.labels" style="width:100%;" :popper-append-to-body="false"
                            popper-class="select-popper" placeholder="请选择">
                            <el-option v-for="item in labelDicts" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
                <div v-else>
                    <el-form-item label="名称" prop="model_name">
                        <label>{{ addForm.name }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
                        <a href="javascript:;" class="start" @click="preAddModel">新增模型</a>
                    </el-form-item>
                </div>
                <h3 class="add-alike-title">版本信息</h3>
                <el-form-item label="版本" prop="version">
                    <el-input type="text" v-model="addForm.version" readonly />
                </el-form-item>
                <el-form-item label="提交信息" prop="commit_msg">
                    <el-input type="textarea" :rows="3" v-model="addForm.commit_msg" />
                </el-form-item>
            </div>

            <div v-if="active == 3">
                <h1 class="succeed-hint">导出成功</h1>
                <div class="succeed-btn">
                    <a href="javascript:;" class="start" @click="cancel">返回</a>
                    <a href="javascript:;" class="go" @click="toModel">立即前往</a>
                </div>
            </div>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button type="primary" v-if="active == 1" @click="fileSubmit">下一步</el-button>
            <el-button type="primary" v-if="active == 2" @click="submmitModelOrVersion">确定</el-button>
        </span>

    </el-dialog>
</template>

<script>
import { labelDicts, zipFormat, mediaFormat } from '@/utils/maps'
import { getPageFileList } from "@/api/file"
import { getExperimentDetail } from '@/api/notebook'
import { getGameExperimentDetail } from '@/api/gameExperiment'
import { getGameTaskVersionDetail ,getGameTaskDetail } from '@/api/gameTask'
import { addModel } from '@/api/model'
import { addModelVersion } from '@/api/modelversion'
import { getModelDetail } from '../../api/model'
import { getTaskVersionDetail ,getTaskDetail} from '@/api/task'
export default {
    data() {
        return {
            addForm: {
                visibility: 0,
                type: '1',
                name: '',
                desc: '',
                alias: '',
                labels: '',
                version: 'v1'
            },
            labelDicts,
            showDialog:false,
            model: {},
            version: {},
            submitRules: {
                name: [
                    { required: true, message: "该项为必填项" },
                    { required: true, min: 1, max: 40, message: "长度在1到40个字符" },
                ],
                alias: [
                  { required: true, message: "该项为必填项" },
                  { required: true, min: 5, max: 40, message: "长度在5到40个字符" },
                  { required: true, pattern: /^[a-z][a-zA-Z0-9]+$/, message: "以小写字母开头且只能输入字母和数字" },
                ],
                desc: [
                    { required: true, message: "该项为必填项" },
                    { required: true, min: 1, max: 200, message: "长度在1到200个字符" },
                ],
                commit_msg: [
                    { required: true, message: "该项为必填项" },
                    { required: true, min: 1, max: 500, message: "长度在1到200个字符" },
                ],
            },
            defaultProps: {
                label: "name",
                children: [],
                isLeaf: "dir",
            },
            active: 1,
            node: {},
            resolve: [],
            defaultCheckNode: [], //默认选中model文件夹和main.py 主文件
        };
    },
    props: ["show_file", "model_id", "biz_id", "business_type"],
    watch: {
        show_file(val) {
            this.showDialog = val
            console.log("show_file", val)
        },
        biz_id(val) {
            console.log("biz_id", val)
        },
        business_type(val) {
            console.log("business_type", val)
        },
        model_id(val) {
            console.log("model_id", val)
        }
    },
    mounted() {
        this.showDialog = this.show_file
        console.log("show_file", this.show_file)
        console.log("biz_id", this.biz_id)
        console.log("business_type", this.business_type)
        console.log("model_id", this.model_id)
        this.doloadNode();
        this.getData()
    },
    methods: {
        async getData() {
            if (this.model_id) {
                let res = await getModelDetail({ id: this.model_id })
                let data = res.data
                this.addForm.name = data.name
                this.addForm.desc = data.desc
                this.addForm.alias = data.alias
                this.addForm.visibility = 0
                let version =data.version_index + 1
                this.addForm.version = 'v'+version

            }
            else{
                if(this.business_type ==1){
                    let res = await getExperimentDetail({ id: this.biz_id })
                    let data = res.data
                    this.addForm.name = data.name
                    this.addForm.desc = data.desc
                    this.addForm.alias = data.alias
                    this.addForm.visibility = 0
                    this.addForm.version = 'v1'
                    this.addForm.type='1'
                }
                if(this.business_type ==2){
                    let res = await getTaskVersionDetail({ id: this.biz_id })
                    let data = res.data
                    let res2 = await getTaskDetail({ id: data.task_id })
                    data = res2.data
                    this.addForm.name = data.name
                    this.addForm.desc = data.desc
                    this.addForm.visibility = 0
                    this.addForm.version = 'v1'
                    this.addForm.type='1'
                }
                if(this.business_type ==3){
                    let res = await getGameExperimentDetail({ id: this.biz_id })
                    let data = res.data
                    this.addForm.name = data.name
                    this.addForm.desc = data.desc
                    this.addForm.visibility = 0
                    this.addForm.version = 'v1'
                    this.addForm.type='2'
                }
                if(this.business_type ==4){
                    let res = await getGameTaskVersionDetail({ id: this.biz_id })
                    let data = res.data
                    console.log("version", data)
                    let res2 = await getGameTaskDetail({ id: data.game_task_id })
                    data = res2.data
                    this.addForm.name = data.name
                    this.addForm.desc = data.desc
                    this.addForm.visibility = 0
                    this.addForm.version = 'v1'
                    this.addForm.type='2'
                }
            }
            this.$forceUpdate()
        },
        preAddModel(){
            this.model_id = null
            this.addForm.version = 'v1'
        },
        fileSubmit() {
            let checkNodeList = this.$refs.tree.getCheckedNodes();
            this.addForm.model_file = []
            for (let i = 0; i < checkNodeList.length; i++) {
                this.addForm.model_file.push(checkNodeList[i].path)
            }
            console.log("abc", this.addForm.model_file)
            if (checkNodeList.length > 0) {
                console.log(checkNodeList)
                this.active = 2
            } else {
                this.$message({
                    message: "请至少勾选一个文件",
                    type: "warning",
                });
            }

            // this.showFile = false
        },
        submmitModelOrVersion() {
            console.log("abc")
            this.$refs.form.validate(async (valid) => {
                if (valid) {
                    if (this.model_id) {
                        console.log("putModel", this.model_id)
                        this.addForm.id = this.model_id
                        let modelVersion = {}
                        modelVersion.business_id = this.biz_id
                        modelVersion.business_type = this.business_type
                        modelVersion.model_id = this.addForm.id
                        modelVersion.version = this.addForm.version
                        modelVersion.file_source ="1"
                        modelVersion.commit_msg = this.addForm.commit_msg
                        modelVersion.model_file = this.addForm.model_file
                        await addModelVersion(modelVersion)
                        this.active = 3
                    }
                    else {
                        this.addForm.business_id = this.biz_id
                        this.addForm.business_type = this.business_type
                        let ret = await addModel({ ...this.addForm });
                        console.log("ret",ret.data)
                        this.addForm = ret.data
                        this.model_id = this.addForm.id
                        this.active = 3
                    }
                }
            })
        },
        doloadNode(node, resolve) {
            console.log("node",node)
            this.loadNode(node, resolve);
        },
        avatarPath(data) {
            this.addForm.avatar = data;
        },
        getRelativePath(node){
            if (node == null){
                console.log("parent is null")
                return ""
            }
            if (node.parent == null){
                console.log("parent is null")
                return ""
            }
            let relative_path = node.data.name
            node = node.parent
            while(node.parent){
                relative_path = node.data.name +"/"+ relative_path
                node = node.parent
            }
            return relative_path
        },
        async loadNode(node, resolve) {
            let myInfo = await this.$myInfo(this)
            //let bizId = this.$route.query.experiment_id
            let relative_path = this.getRelativePath(node)
            let paramters = {
                biz_id: this.biz_id,
                relative_path,
                type: 'workspace',
                user_id: myInfo.id,
                page_num: 1,
                page_size: 200,
            };
            this.defaultCheckNode = this.$refs.tree.getCheckedKeys()
            let defaultFileList = await getPageFileList(paramters);
            this.defaultFileList = defaultFileList.data.list && defaultFileList.data.list;
            this.defaultFileList.map((item) => {
                return (item.dir = item.dir == true ? false : true);
            });
            console.log("defaultFileList", this.defaultFileList)
            console.log("resolve", resolve)
            if (this.defaultFileList) {
                return resolve(this.defaultFileList);
            }

        },
        handleClass({ dir, suffix }) {
            if (zipFormat[suffix]) return "zip";
            if (mediaFormat[suffix]) return mediaFormat[suffix]
            if (!dir) return "dir";
            return "text";
        },
        cancel() {
            this.showDialog = false
            this.$emit('update:show_file', false) 
        },
        toModel() {
            if(this.business_type>2){
                //强化学习
                this.$router.push({ path: '/gameModel/code', query: { id: this.model_id } })
            }
            else{
                this.$router.push({ path: '/model/code', query: { id: this.model_id } })
            }
        }
    }
}
</script>
<style lang="less" scoped>
@import "~@/assets/css/detail-add.less";
</style>